package com.jdy.haoduoaiteacher.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.jdy.haoduoaiteacher.MyTeacherApp;
import com.jdy.haoduoaiteacher.adapter.ImageGridAdapter;
import com.jdy.haoduoaiteacher.intface.IAsyncTask;
import com.jdy.haoduoaiteacher.model.ImageItem;
import com.jdy.haoduoaiteacher.model.LeUser;
import com.jdy.haoduoaiteacher.util.CommonUtil;
import com.jdy.haoduoaiteacher.util.CustomAsyncTask;
import com.jdy.haoduoaiteacher.util.CustomConstants;
import com.jdy.haoduoaiteacher.util.HttpUtils;
import com.jdy.haoduoaiteacher.util.IntentConstants;
import com.jdy.haoduoaiteacher.util.ResponseResult;
import com.jdy.haoduoaiteacher.util.Tools;
import com.ycsj.goldmedalnewconcept.R;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

//import com.jdy.haoduoaiteacher.R;

/**
 * 图片选择
 */
public class ImageChooseActivity extends BaseActivity {
    private List<ImageItem> mDataList = new ArrayList<ImageItem>();
    private String mBucketName;
    private int availableSize;
    private GridView mGridView;
    private TextView mBucketNameTv;
    private TextView cancelTv;
    private View view_upload;
    private ImageGridAdapter mAdapter;
    private Button mFinishBtn;
    private boolean isEditable = true;
    private ImageView photo_bt_share;
    private View photo_relativeLayout;
    private boolean mFromAddHabitClockActivity = false;
    private boolean mFromPublishPhotoActivity = false;
    private String mmmacid;

    private HashMap<String, ImageItem> selectedImgs = new HashMap<String, ImageItem>();

    @SuppressWarnings("unchecked")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.act_image_choose_teacher);

        mDataList = (List<ImageItem>) getIntent().getSerializableExtra(
                IntentConstants.EXTRA_IMAGE_LIST);
        if (mDataList == null)
            mDataList = new ArrayList<ImageItem>();
        mBucketName = getIntent().getStringExtra(IntentConstants.EXTRA_BUCKET_NAME);

        mFromAddHabitClockActivity = getIntent().getBooleanExtra("FromAddHabitClockActivity", false);

        mFromPublishPhotoActivity  = getIntent().getBooleanExtra("FromPublishPhotoActivity", false);

        mmmacid = getIntent().getStringExtra("macid");

        if (TextUtils.isEmpty(mBucketName)) {
            mBucketName = "请选择";
        }

        mBackImageButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // Intent intent = new Intent(ImageChooseActivity.this,
                // PublishActivity.class);
                // startActivity(intent);

                finish();
            }
        });

        // photo_relativeLayout.setVisibility(View.VISIBLE);

        // mTvUpright.setOnClickListener(new OnClickListener() {
        //
        // @Override
        // public void onClick(View v) {
        // // isEditable = !isEditable;
        // // if (!isEditable) {
        // // mTvUpright.setVisibility(View.GONE);
        // // img_upright.setVisibility(View.VISIBLE);
        // // // mTvUpright.setText("取消");
        // // }
        //
        // if (mAdapter != null) {
        // mAdapter.setEditable(isEditable);
        // mAdapter.notifyDataSetChanged();
        // }
        //
        // photo_relativeLayout.setVisibility(View.VISIBLE);
        //
        // // if (isEditable)
        // //
        // // else
        // // photo_relativeLayout.setVisibility(View.GONE);
        // }
        //
        // });
        //
        // img_upright.setVisibility(View.VISIBLE);
        // img_upright.setImageResource(R.drawable.icon_edit);
        // img_upright.setOnClickListener(new OnClickListener() {
        //
        // @Override
        // public void onClick(View v) {
        // // isEditable = !isEditable;
        //
        // if (isEditable) {
        // mTvUpright.setVisibility(View.VISIBLE);
        // img_upright.setVisibility(View.GONE);
        // mTvUpright.setTextColor(0xffffffff);
        // mTvUpright.setText("取消");
        // }
        //
        // if (mAdapter != null) {
        // mAdapter.setEditable(isEditable);
        // mAdapter.notifyDataSetChanged();
        // }
        //
        // if (isEditable)
        // photo_relativeLayout.setVisibility(View.VISIBLE);
        // else
        // photo_relativeLayout.setVisibility(View.GONE);
        // }
        // });

        setTitle("所有照片");

        availableSize = getIntent().getIntExtra(
                IntentConstants.EXTRA_CAN_ADD_IMAGE_SIZE,
                CustomConstants.MAX_IMAGE_SIZE);

        initView();
        initListener();

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            // Intent intent = new Intent(ImageChooseActivity.this,
            // PublishActivity.class);
            // startActivity(intent);

            return true;

        }
        return super.onKeyDown(keyCode, event);
    }

    private int total;

    private void initView() {
        mBucketNameTv = (TextView) findViewById(R.id.title);
        mBucketNameTv.setText(mBucketName);

        mGridView = (GridView) findViewById(R.id.gridview);
        mGridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
        mAdapter = new ImageGridAdapter(ImageChooseActivity.this, mDataList);
        mGridView.setAdapter(mAdapter);
        mFinishBtn = (Button) findViewById(R.id.finish_btn);
        // cancelTv = (TextView) findViewById(R.id.action);
        photo_relativeLayout = findViewById(R.id.photo_relativeLayout);
        photo_bt_share = (ImageView) findViewById(R.id.photo_bt_share);
        photo_bt_share.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);
        photo_bt_share.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (selectedImgs == null) {
                    return;
                }

                ArrayList<ImageItem> alist = new ArrayList<ImageItem>(selectedImgs
                        .values());

                if (alist == null || alist.isEmpty()) {
                    return;
                }

                if (alist.size() == 0) {
                    toastShow("请选择图片");
                    return;
                } else {
                    // AndroidShare as = new AndroidShare(ImageChooseActivity.this,
                    // "分享宝宝照片", alist.get(0).sourcePath);
                    // as.show();
                    // Intent intent = new Intent(ImageChooseActivity.this,
                    // SharePopupWindow.class);
                    // intent.putExtra("picList", alist);
                    // intent.putExtra("localpic", true);
                    // intent.putExtra("sharepic", true);
                    // startActivity(intent);

                    Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
                    intent.setType("image/*");

                    ArrayList<Uri> myList = new ArrayList<Uri>();
                    for (int i = 0; i < alist.size(); i++) {
                        try {
                            myList.add(Uri.fromFile(new File(alist.get(i).sourcePath)));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, myList);
                    intent.putExtra(Intent.EXTRA_SUBJECT, "分享");
                    intent.putExtra(Intent.EXTRA_TITLE, "宝宝照片");
                    intent.putExtra(Intent.EXTRA_TEXT, "宝宝照片");
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                    startActivity(Intent.createChooser(intent, "请选择"));
                }
            }
        });

        if (isEditable) {
            photo_relativeLayout.setVisibility(View.VISIBLE);
        } else {
            photo_relativeLayout.setVisibility(View.GONE);
        }

        view_upload = findViewById(R.id.view_upload);
        view_upload.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent;

                if (mFromAddHabitClockActivity) {
                    intent = new Intent(ImageChooseActivity.this,
                            AddHabitClockActivity.class);
                    intent.putExtra(IntentConstants.EXTRA_IMAGE_LIST,
                            new ArrayList<ImageItem>(selectedImgs.values()));
                    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
                            | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                    finish();
                } else if (mFromPublishPhotoActivity) {
                     if (selectedImgs == null) {
                     return;
                     }

                     ArrayList<ImageItem> alist = new ArrayList<ImageItem>(selectedImgs
                     .values());

                     if (alist == null || alist.isEmpty()) {
                     return;
                     }

                     showloading("");

                     for (final ImageItem item : alist) {
                         uploadImageFile(item.sourcePath);
                     }
                }





            }
        });

        mAdapter.setEditable(isEditable);
        // mFinishBtn.setText("上传到宝宝的云相册");
        mAdapter.notifyDataSetChanged();
    }



    private void uploadImageFile(final String filePath) {
         // showloading("");
        new CustomAsyncTask(this, new IAsyncTask() {
            @Override
            public void onRecieveData(Activity activity, ResponseResult result) {
                if (result.isSuccess()) {
                   final String imgUrl_toSubmit = result.data;
                    if (Tools.isNotEmpty(imgUrl_toSubmit)) {
                        new CustomAsyncTask(ImageChooseActivity.this, new IAsyncTask() {
                            @Override
                            public void onRecieveData(Activity activity, ResponseResult result) {
                                if (result.isSuccess()) {
                                    ++total;
                                    if (total == selectedImgs.size()) {
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                dismissLoading();

                                                toastShow("上传完毕!");
                                                Intent intent = new Intent(
                                                        ImageChooseActivity.this, PublishPhotoActivity.class);
                                                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                                startActivity(intent);

                                                ImageChooseActivity.this.finish();
                                            }
                                        });

                                    }
                                } else {
                                    dismissLoading();
                                    toastShow(result.data);
                                }
                            }

                            @Override
                            public ResponseResult doInbackground(Activity activity) {
                                HashMap<String, Object> param_ = new HashMap<String, Object>();
                                LeUser lu = MyTeacherApp.getInstance().getUserTeacher();
                                if (lu == null) {
                                    lu = Tools.restoreLeUser();
                                }
                                param_.put(HttpUtils.TAG_SNO_I, lu.sno);
                                param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
                                param_.put("macid", mmmacid);
                                param_.put("url", imgUrl_toSubmit);
                                return HttpUtils.startRequest(HttpUtils.HOST_API
                                                + "/api/2.0/teacher/teacher_photo", param_,
                                        HttpUtils.TAG_POST_REQUEST);

                            }
                        }).execute("请检查网络连接!");
                    }
                } else {

                    toastShow(result.data);
                }

               // dismissLoading();
            }

            @Override
            public ResponseResult doInbackground(Activity activity) {
                HashMap<String, Object> param_ = new HashMap<String, Object>();
                LeUser lu = MyTeacherApp.getInstance().getUserTeacher();
                if (lu == null) {
                    lu = Tools.restoreLeUser();
                }
                param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
                param_.put(HttpUtils.TAG_SNO_I, lu.sno);
                param_.put(HttpUtils.TAG_MODULE_I, "teacher/photo");
                return HttpUtils.startUploadRequest(HttpUtils.API_URL
                                + HttpUtils.UPLOAD_BABY_AVATAR_POST, param_, "Filedata", filePath,
                        HttpUtils.TAG_POST_REQUEST);

            }
        }).execute("请检查网络连接!");
    }

    private void initListener() {
        // mFinishBtn.setOnClickListener(new OnClickListener() {
        //
        // @Override
        // public void onClick(View v) {
        // // Intent intent = new Intent(ImageChooseActivity.this,
        // // PublishActivity.class);
        // // intent.putExtra(IntentConstants.EXTRA_IMAGE_LIST,
        // // new ArrayList<ImageItem>(selectedImgs.values()));
        // // startActivity(intent);
        // // finish();
        // }
        //
        // });

        mGridView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                                    long id) {

                if (isEditable) {
                    ImageItem item = mDataList.get(position);
                    if (item.isSelected) {
                        item.isSelected = false;
                        selectedImgs.remove(item.imageId);
                    } else {
                        if (selectedImgs.size() >= availableSize) {
                            Toast.makeText(ImageChooseActivity.this,
                                    "最多选择" + availableSize + "张图片", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        item.isSelected = true;
                        selectedImgs.put(item.imageId, item);
                    }

                    if (mFromAddHabitClockActivity) {
                        mFinishBtn.setText("完成");
                    } else {
                        mFinishBtn.setText("完成" + "(" + selectedImgs.size() + "/"
                                + availableSize + ")");
                    }

                    mAdapter.notifyDataSetChanged();
                }
            }
        });

        // cancelTv.setOnClickListener(new OnClickListener() {
        //
        // @Override
        // public void onClick(View v) {
        // // Intent intent = new Intent(ImageChooseActivity.this,
        // // PublishActivity.class);
        // // startActivity(intent);
        // }
        // });

    }
}